package com.xl.bigdata.es.index;

import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MultiGetApi
 * @Description TODO
 * @Author xl.gao
 * @Date 2022/1/4 10:12
 * @Version
 */
public class MultiGetApi {

    /**
     * @Description:根据index和多个ID获取多个get
     * @Author: xl.gao
     * @Date:
     * @param client:
     * @param mapIndex: key:index,value:id
     * @return: java.util.Map<java.lang.String,java.lang.String> key:index_id,value:json
     **/
    public static Map<String, String> multiGetAPI(RestHighLevelClient client, Map<String, String> mapIndex) {

        Map<String, String> mapResult = new HashMap<>();

        MultiGetRequest multiGetRequest = new MultiGetRequest();

        for (String key : mapIndex.keySet()) {
            multiGetRequest.add(new MultiGetRequest.Item(key, mapIndex.get(key)));
        }

        try {
            MultiGetResponse mgetResponse = client.mget(multiGetRequest, RequestOptions.DEFAULT);

            for (MultiGetItemResponse multiGetItemResponse : mgetResponse) {
                String index = multiGetItemResponse.getIndex();
                String id = multiGetItemResponse.getId();
                String json = multiGetItemResponse.getResponse().getSourceAsString();

                mapResult.put(index + "_" + id, json);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return mapResult;
    }
}
